﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using WF_Business.Script;
using ExtBusiness;
using ExtBusiness.FlowOperation;
using System.Text;
using ExtBusiness.Interface;
using ExtBusiness.CommonBusiness;
using WF_DataAccess;
using ChBusiness;
using ChBusiness.CommonBusiness;
using WF_Business;

/// <summary>
///WebFormService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/", Description = "jquery交互服务")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。 
[System.Web.Script.Services.ScriptService]
public class JueryService : System.Web.Services.WebService
{
    /// <summary>
    /// 获取下一个岗位
    /// </summary>
    /// <param name="wid">流程id</param>
    /// <param name="step">岗位名称</param>
    /// <param name="iid">办件编号</param>
    /// <param name="wiid">办件中环节编号</param>
    /// <returns></returns>
    [WebMethod]
    public string GetNextSteps(string wid, string step, long iid, long wiid)
    {
        DataTable dtStep = WorkFlowStep.GetNextStepByStep(wid, step, iid, wiid);
        StringBuilder sb = new StringBuilder();
        foreach (DataRow drStep in dtStep.Rows)
        {
            sb.Append("<span>");
            sb.Append("<input type='Radio' name='steps' value='" + drStep["fname"] + "' " +
                "onclick=\"OnStepSelect('" + drStep["extend_type"] + "',this)\" /><font style=\"font-size:16px;font-family: Tohoma\">" + drStep["fname"] + "</font>");
            sb.Append("<input type='Hidden' name='" + drStep["fname"] + "' value='" + drStep["ename"] + "' />");
            sb.Append("</span>&nbsp;");
        }
        return sb.ToString();
    }

    /// <summary>
    /// 根据流向获取角色列表
    /// </summary>
    /// <param name="nItemId">办件中环节编号</param>
    /// <param name="iid">办件编号</param>
    /// <param name="flow">流程名称</param>
    /// <returns></returns>
    [WebMethod]
    public string GetRoleList(Int64 nItemId, long iid, string flow)
    {
        string sql = "SELECT stepctlid,stepgroupctlid FROM ST_WORK_ITEM WHERE iid='" + iid.ToString() + "' AND wiid=" + nItemId.ToString();
        DataTable dtWorkItem;
        SysParams.OAConnection().RunSql(sql, out dtWorkItem);

        if (dtWorkItem.Rows.Count > 0)
        {
            string nowStep = dtWorkItem.Rows[0]["STEPCtlid"].ToString();//当前节点的控制ID
            if (!String.IsNullOrEmpty(dtWorkItem.Rows[0]["stepgroupctlid"].ToString()))//节点组名称不为空的话，说明节点组名称才是定义中的节点名称
                nowStep = dtWorkItem.Rows[0]["stepgroupctlid"].ToString();
            StepType stepType = WorkFlowStep.GetStepType(iid, flow, nowStep);

            if (stepType == StepType.End || stepType == StepType.EndNotAccept || stepType == StepType.EndNotTransact)
            {
                return "#END#";
            }
        }

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<result method='1'>");

        string strWid = WorkFlowResource.GetWidByIID(iid.ToString());
        DataTable dt = RequestFlows.GetRolesInStep(strWid, flow);
        sb.Append("<out method='1'>");

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strFlowName = dt.Rows[i][0].ToString();
            sb.Append("<flow type='1'>");
            sb.Append(strFlowName);
            sb.Append("</flow>");
        }
        sb.Append("</out>");
        sb.Append("</result>");
        return sb.ToString();
    }

    /// <summary>
    /// 获取下一岗位的用户
    /// </summary>
    /// <param name="nItemId">办件中环节编号</param>
    /// <param name="iid">办件编号</param>
    /// <param name="strName">岗位名称</param>
    /// <param name="findMode">查找模式，0：通过流向查找，1：通过角色查找</param>
    /// <returns></returns>
    [WebMethod]
    public string GetUserInStep(Int64 nItemId, long iid, string strName, string findMode)
    {
        string sql = "SELECT stepctlid,stepgroupctlid FROM ST_WORK_ITEM WHERE iid='" + iid.ToString() + "' AND wiid=" + nItemId.ToString();
        DataTable dtWorkItem;
        SysParams.OAConnection().RunSql(sql, out dtWorkItem);

        string nowStep = "";
        if (dtWorkItem.Rows.Count > 0)
        {
            nowStep = dtWorkItem.Rows[0]["STEPCtlid"].ToString();//当前节点的控制ID
            if (!String.IsNullOrEmpty(dtWorkItem.Rows[0]["stepgroupctlid"].ToString()))//节点组名称不为空的话，说明节点组名称才是定义中的节点名称
                nowStep = dtWorkItem.Rows[0]["stepgroupctlid"].ToString();
        }

        DataTable dt = new DataTable();
        //取得所有流向的下一节点的所有用户组的所有用户
        StepType stepType = new StepType();
        if (findMode == "0")   //通过流向查找
        {
            stepType = WorkFlowStep.GetStepType(iid, strName, nowStep);

            if (stepType == StepType.End||stepType == StepType.EndNotAccept||stepType == StepType.EndNotTransact)
            {
                return "#END#";
            }
            else if (strName == "岗位内提交" || (stepType != StepType.End && stepType != StepType.EndNotAccept && stepType != StepType.EndNotTransact))
            {
                dt = new WorkFlowStep().GetStepAllNextUsers(iid, nItemId, strName);
                //dt = RequestFlows.GetNextStepAllUsers(iid, nItemId, strName);
            }
        }
        else if (findMode == "1") //通过角色查找
        {
            stepType = WorkFlowStep.GetStepTypeByStep(iid, strName);
            if (stepType == StepType.End||stepType == StepType.EndNotAccept||stepType == StepType.EndNotTransact)
            {
                return "#END#";
            }
            else if (strName == "岗位内提交" || (stepType != StepType.End && stepType != StepType.EndNotAccept && stepType != StepType.EndNotTransact))
            {
                dt = WorkFlowStep.GetUsersInStep(iid, nItemId, strName);
            }
        }

        if (dt.Rows.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in dt.Rows)
            {
                if (!sb.ToString().Equals(""))
                    sb.Append(";");
                sb.Append(dr["UserId"].ToString() + "|" + dr["User_Name"].ToString());
            }
            return sb.ToString();
        }
        else
        {
            return "#ERROR#";
        }
    }

    /// <summary>
    /// 设置信息
    /// </summary>
    /// <param name="strIID">办件编号</param>
    /// <param name="strField">字段名</param>
    [WebMethod]
    public void SetSubmitFlag(string strIID, string strField)
    {
        ClsSubmitInfo ioTemp = new ClsSubmitInfo();
        ioTemp.SetSubmitFlag(strIID, strField);
    }

    /// <summary>
    /// 设置预审通过
    /// </summary>
    /// <param name="strIID">办件编号</param>
    /// <param name="nFlag">操作标志位</param>
    [WebMethod]
    public string SetYsFlag(string strIID,int nFlag)
    {
        ClsSubmitInfo ioTemp = new ClsSubmitInfo();
        if (nFlag == 1)//设置为通过
        {
            ioTemp.SetYsFlag(strIID,3);
            ioTemp.SetMsg(strIID, "预审通过");
        }
        else if (nFlag == -1)//设置为不通过
        {
            ioTemp.SetYsFlag(strIID, 1);
        }

        return strIID;
    }

    /// <summary>
    /// 设置通过、协议通过或不通过决定时更新状态位
    /// </summary>
    /// <param name="strIID">办件编号</param>
    /// <param name="strStatus">status状态</param>
    [WebMethod]
    public string SetPassFlag(string strIID, string strStatus)
    {
        RequestFlowOperation rfo = new RequestFlowOperation();
        rfo.UpdatePassStatus(strIID, strStatus);
        return strStatus;
    }

    /// <summary>
    /// 更新表信息
    /// </summary>
    /// <param name="strTableName">表名</param>
    /// <param name="strFieldName">列名</param>
    /// <param name="strFieldValue">字段名</param>
    /// <param name="strWhere">条件</param>
    [WebMethod]
    public void UpdateTableInfo(string strTableName,string strFieldName,string strFieldValue, string strWhere)
    {
        OracleSystemOperation ioTemp = new OracleSystemOperation();
        ioTemp.UpdateTableValue(strTableName,strFieldName,strFieldValue,strWhere);
    }

    /// <summary>
    /// 创建地图审核流程
    /// </summary>
    /// <param name="strWid">流程id</param>
    /// <param name="strWorkFlowName">流程名称</param>
    /// <param name="strUserName">申请单位名称</param>
    /// <param name="strAppid">对应的关联iid</param>
    /// <param name="strUserId">创建人id</param>
    /// <param name="strIsNw">是否是内网直接受理的变更案件（1：内网受理,0:外网受理）</param>
    /// <param name="strDtyt">地图用途</param>
    /// <param name="strSbUserid">申报用户id</param>
    /// <returns></returns>
    [WebMethod]
    public string BuildMapSerial(string strWid, string strWorkFlowName, string strUserName, string strAppid, string strUserId, string strIsNw, string strDtyt, string strSbUserid)
    {
        //创建流程实例
        WorkFlow work = new WorkFlow();
        string iid = "", wiid = "", errmsg = "";
        String strSql = string.Empty;
        iid = strAppid;

        //特殊流程与申请表不参共享iid
        if (strWorkFlowName == "地图审核变更审批" || strWorkFlowName == "地图审核延期审批" || strWorkFlowName == "地图审核撤销审批")
        {
            iid = "";
        }

        IDataAccess dataAccess = SysParams.OAConnection(true);
        try
        {
            if (true == work.NewInstance(strWid, strUserId, strUserName, ref iid, ref wiid, ref errmsg, ref dataAccess))
            {
                strSql = string.Format(@"insert into xt_instance_ext(iid,申请单位,联系人,关联ID,status,IS_NW,DTYT) values({0},'{1}','{2}','{3}','0','{4}','{5}')", iid, strUserName, strUserName, strAppid, strIsNw, strDtyt);
                dataAccess.RunSql(strSql);

                if (strWorkFlowName == "地图审核(即送即审)")
                {
                    strSql = string.Format(@"update st_instance set PRIORITY='2' where iid='{0}'", iid);
                    dataAccess.RunSql(strSql);
                }

                OracleSystemOperation osoTemp = new OracleSystemOperation();
                HandleCaseService hcsTemp = new HandleCaseService();

                //分流程类型来添加表单数据 addby zhongjian 20100311
                switch (strWorkFlowName)
                {
                    case "国家涉密基础测绘成果使用申报":// 将外网申报信息id(strAppid)和内网审批系统中刚刚生成的iid做好对应关系
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_测绘成果使用申请表", dataAccess);
                        break;
                    case "地图审核变更审批":
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_国家测绘局地图审核申请表", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核受理通知书", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核变更申请单", dataAccess);

                        hcsTemp.AddSuspend(strAppid, strUserId, strWorkFlowName, iid);//挂起对应的流程
                        break;
                    case "地图审核延期审批":
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_国家测绘局地图审核申请表", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核受理通知书", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核延期申请单", dataAccess);
                        hcsTemp.AddSuspend(strAppid, strUserId, strWorkFlowName, iid);//挂起对应的流程
                        break;
                    case "地图审核撤销审批":
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_国家测绘局地图审核申请表", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核受理通知书", dataAccess);
                        osoTemp.GetNewTaskSql(iid, strAppid, "UT_地图审核撤销申请单", dataAccess);
                        hcsTemp.AddSuspend(strAppid, strUserId, strWorkFlowName, iid);//挂起对应的流程
                        break;
                    default:
                        break;
                }

                //添加操作日志,获取操作者ip地址
                string myIP = Common.IPOperation.GetIpAddress();
                //操作描述
                string strRemark = "受理申请编号为: " + strAppid + " 受理编号为: " + iid + " 的案件;流程类型为:" + strWorkFlowName + "";
                SystemLogs.AddSystemLogs(strUserId, "add", strRemark, "", myIP);

                //先删除已有的附件内容,针对补正补齐重复提交的情况 addby zhongjian 20100326
                strSql = string.Format(@"delete from st_attachment where aid in (select id from XT_SERIAL_ATTACHMENT where AppDataId = '{0}' or (userid='{1}' and IS_TEMPLET=1))", strAppid, strSbUserid);
                dataAccess.RunSql(strSql);

                //插入受理附件表 addby zhongjian 20091030
                strSql = string.Format(@"insert into st_attachment(aid,magic_number,ext_name,data,name) select id,'1','.'||filetype,filedata,filename from XT_SERIAL_ATTACHMENT where AppDataId='{0}' or (userid='{1}' and IS_TEMPLET=1)", strAppid,strSbUserid);
                dataAccess.RunSql(strSql);

                //插入受理动态目录表,附件地址按流程类型分类,并添加附件后缀名
                string strAttPath = "扫描资料/申请资料/";
                switch (strWorkFlowName)
                {
                    case "国家涉密基础测绘成果使用申报"://涉密流程处理表单时查看附件的地址.
                        strAttPath = "扫描资料/申请资料/";
                        break;
                    case "地图审核(即送即审)":
                    case "地图审核(5日协审)":
                    case "地图审核(7日)":
                    case "地图审核(20日)":
                        strAttPath = "扫描资料/";
                        break;
                    case "永久性测量标志拆迁审批":
                        strAttPath = "电子附件/";
                        break;
                    case "DTSH_地图审核程序流程图":
                    case "地图审核变更审批":
                    case "地图审核延期审批":
                    case "地图审核撤销审批":
                        strAttPath = "";//根目录为空
                        break;
                    default:
                        break;
                }


                //strSql = string.Format(@"insert into st_dynamic_resource(iid,path,sname,userid,type,res_value) select '{0}','{3}'||filename||'.'||filetype,'受理窗口','{1}','2',id from XT_SERIAL_ATTACHMENT where AppDataId='{2}'", iid, strUserId, strAppid, strAttPath);
                strSql = string.Format(@"insert into st_dynamic_resource(iid,path,sname,userid,type,res_value) select '{0}','{3}'||(select decode(a.modulename,null,'',a.modulename||'/') from xt_serial_module a where a.id = t.module_id)||filename||'.'||filetype,'窗口受理','{1}','2',id from XT_SERIAL_ATTACHMENT t where AppDataId='{2}' or (userid='{4}' and IS_TEMPLET=1)", iid, strUserId, strAppid, strAttPath,strSbUserid);
                dataAccess.RunSql(strSql);

                dataAccess.Close(true);
            }
            else
            {
                dataAccess.Close(false);//回滚
                
                throw new Exception(errmsg);
            }
        }
        catch(Exception ex)
        {
            Common.Log.LogManage.addLogErr("BuildMapSerial", ex.Message);
            dataAccess.Close(false);
            throw;
        }

        //发送消息
        ClsSubmitInfo clsSubmit = new ClsSubmitInfo();
        clsSubmit.SetMsg(strAppid, "业务受理");

        return iid;
    }

    /// <summary>
    /// 根据办件编号获取申报信息并拷贝添加
    /// </summary>
    /// <param name="strOldIid"></param>
    /// <param name="strUserId"></param>
    /// <returns></returns>
    [WebMethod]
    public string CopyAndAdd(string strOldIid, string strUserId)
    {
        ExtBusiness.FlowOperation.RequestFlowOperation flowOperation = new ExtBusiness.FlowOperation.RequestFlowOperation();
        return flowOperation.CopyAndAdd(strOldIid, strUserId);
    }

    /// <summary>
    /// 获取待办信息
    /// </summary>
    /// <param name="strUserId">用户名</param>
    /// <param name="strOldDbCount">初始待办数目</param>
    /// <returns></returns>
    [WebMethod]
    public string GetDaiBan(string strUserId, string strOldDbCount)
    {
        string strReturn = "";
        if (!string.IsNullOrEmpty(strOldDbCount))
        {
            string[] arrOld = strOldDbCount.Split('|');
            DataTable dtReturn = new DataTable();

            if (arrOld.Length > 1)
            {
                ClsSubmitInfo clsSubmit = new ClsSubmitInfo();
                dtReturn = clsSubmit.GetBusinessInfo(strUserId, "", "", "", "0");//待预审

                if (Convert.ToInt32(arrOld[0]) < dtReturn.Rows.Count)
                {
                    strReturn = string.Format("dys_gs:'{0}'",dtReturn.Rows.Count);
                }

                dtReturn = clsSubmit.GetBusinessInfo(strUserId, "", "", "", "1");//待补正受理
                if (Convert.ToInt32(arrOld[1]) < dtReturn.Rows.Count)
                {
                    if (!string.IsNullOrEmpty(strReturn))
                    {
                        strReturn +=string.Format(",dbz_gs:'{0}'", dtReturn.Rows.Count);
                    }
                    else
                    {
                        strReturn = string.Format("dbz_gs:'{0}'", dtReturn.Rows.Count);
                    }
                }
            }

            RequestFlowOperation flowOperation = new RequestFlowOperation();
            dtReturn = flowOperation.AppearTaskInStep(strUserId, "",0);//待办件
            if (Convert.ToInt32(arrOld[arrOld.Length-1]) < dtReturn.Rows.Count)
            {
                if (!string.IsNullOrEmpty(strReturn))
                {
                    strReturn += string.Format(",dbj_gs:'{0}'", dtReturn.Rows.Count);
                }
                else
                {
                    strReturn = string.Format("dbj_gs:'{0}'", dtReturn.Rows.Count);
                }
            }

            if (!string.IsNullOrEmpty(strReturn))
            {
                strReturn = "{" + strReturn + "}";
            }
        }
        return strReturn;
    }
}

